import axios from 'axios';

export class CloudService {
  private providers = {
    baidu: {
      name: '百度网盘',
      baseUrl: 'https://pan.baidu.com/rest/2.0/xpan',
      authUrl: 'https://openapi.baidu.com/oauth/2.0'
    },
    aliyun: {
      name: '阿里云盘',
      baseUrl: 'https://api.aliyundrive.com/v2',
      authUrl: 'https://auth.aliyundrive.com/v2/oauth'
    },
    xunlei: {
      name: '迅雷网盘',
      baseUrl: 'https://api-pan.xunlei.com/drive/v1',
      authUrl: 'https://login.xunlei.com/oauth2'
    },
    quark: {
      name: '夸克网盘',
      baseUrl: 'https://drive.quark.cn/1/clouddrive/file',
      authUrl: 'https://account.quark.cn/oauth'
    }
  };

  async listFiles(provider: string, token: string, path: string = '/') {
    const config = this.providers[provider as keyof typeof this.providers];
    if (!config) {
      throw new Error(`Unsupported provider: ${provider}`);
    }

    try {
      switch (provider) {
        case 'baidu':
          return await this.listBaiduFiles(token, path);
        case 'aliyun':
          return await this.listAliyunFiles(token, path);
        case 'xunlei':
          return await this.listXunleiFiles(token, path);
        case 'quark':
          return await this.listQuarkFiles(token, path);
        default:
          throw new Error(`Provider ${provider} not implemented`);
      }
    } catch (error) {
      throw new Error(`Failed to list files: ${(error as Error).message}`);
    }
  }

  async getDownloadUrl(provider: string, token: string, fileId: string) {
    const config = this.providers[provider as keyof typeof this.providers];
    if (!config) {
      throw new Error(`Unsupported provider: ${provider}`);
    }

    try {
      switch (provider) {
        case 'baidu':
          return await this.getBaiduDownloadUrl(token, fileId);
        case 'aliyun':
          return await this.getAliyunDownloadUrl(token, fileId);
        case 'xunlei':
          return await this.getXunleiDownloadUrl(token, fileId);
        case 'quark':
          return await this.getQuarkDownloadUrl(token, fileId);
        default:
          throw new Error(`Provider ${provider} not implemented`);
      }
    } catch (error) {
      throw new Error(`Failed to get download URL: ${(error as Error).message}`);
    }
  }

  async searchFiles(provider: string, token: string, keyword: string, path: string = '/') {
    const files = await this.listFiles(provider, token, path);
    return files.filter((file: any) => 
      file.name.toLowerCase().includes(keyword.toLowerCase())
    );
  }

  async getUserInfo(provider: string, token: string) {
    const config = this.providers[provider as keyof typeof this.providers];
    if (!config) {
      throw new Error(`Unsupported provider: ${provider}`);
    }

    try {
      switch (provider) {
        case 'baidu':
          return await this.getBaiduUserInfo(token);
        case 'aliyun':
          return await this.getAliyunUserInfo(token);
        case 'xunlei':
          return await this.getXunleiUserInfo(token);
        case 'quark':
          return await this.getQuarkUserInfo(token);
        default:
          throw new Error(`Provider ${provider} not implemented`);
      }
    } catch (error) {
      throw new Error(`Failed to get user info: ${(error as Error).message}`);
    }
  }

  // 百度网盘实现
  private async listBaiduFiles(token: string, path: string) {
    const response = await axios.get('https://pan.baidu.com/rest/2.0/xpan/file', {
      params: {
        method: 'list',
        access_token: token,
        dir: path,
        web: 1,
        folder: 0
      }
    });
    
    return response.data.list?.map((file: any) => ({
      id: file.fs_id,
      name: file.server_filename,
      size: file.size,
      type: file.isdir ? 'folder' : 'file',
      path: file.path,
      modified: new Date(file.server_mtime * 1000),
      downloadUrl: file.isdir ? null : `baidu://${file.fs_id}`
    })) || [];
  }

  private async getBaiduDownloadUrl(token: string, fileId: string) {
    const response = await axios.get('https://pan.baidu.com/rest/2.0/xpan/multimedia', {
      params: {
        method: 'filemetas',
        access_token: token,
        fsids: `[${fileId}]`,
        dlink: 1
      }
    });
    
    return response.data.list?.[0]?.dlink || null;
  }

  private async getBaiduUserInfo(token: string) {
    const response = await axios.get('https://pan.baidu.com/rest/2.0/xpan/nas', {
      params: {
        method: 'uinfo',
        access_token: token
      }
    });
    
    return {
      username: response.data.baidu_name,
      uid: response.data.uk,
      quota: response.data.quota,
      used: response.data.used
    };
  }

  // 阿里云盘实现
  private async listAliyunFiles(token: string, path: string) {
    const driveId = await this.getAliyunDriveId(token);
    
    const response = await axios.post('https://api.aliyundrive.com/v2/file/list', {
      drive_id: driveId,
      parent_file_id: path === '/' ? 'root' : path,
      limit: 100,
      all: false,
      url_expire_sec: 1600,
      fields: '*',
      order_by: 'updated_at',
      order_direction: 'DESC'
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    return response.data.items?.map((file: any) => ({
      id: file.file_id,
      name: file.name,
      size: file.size || 0,
      type: file.type,
      path: file.path,
      modified: new Date(file.updated_at),
      downloadUrl: file.type === 'file' ? file.download_url : null
    })) || [];
  }

  private async getAliyunDownloadUrl(token: string, fileId: string) {
    const driveId = await this.getAliyunDriveId(token);
    
    const response = await axios.post('https://api.aliyundrive.com/v2/file/get_download_url', {
      drive_id: driveId,
      file_id: fileId
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    return response.data.url || null;
  }

  private async getAliyunDriveId(token: string) {
    const response = await axios.post('https://api.aliyundrive.com/v2/user/get', {}, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    return response.data.default_drive_id;
  }

  private async getAliyunUserInfo(token: string) {
    const response = await axios.post('https://api.aliyundrive.com/v2/user/get', {}, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    return {
      username: response.data.user_name,
      uid: response.data.user_id,
      quota: response.data.personal_space_info?.total_size || 0,
      used: response.data.personal_space_info?.used_size || 0
    };
  }

  // 迅雷网盘实现
  private async listXunleiFiles(token: string, path: string) {
    const response = await axios.get('https://api-pan.xunlei.com/drive/v1/files', {
      params: {
        parent_id: path === '/' ? '0' : path,
        limit: 100,
        order: 'user_utime',
        direction: 'DESC'
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    return response.data.files?.map((file: any) => ({
      id: file.id,
      name: file.name,
      size: file.size || 0,
      type: file.kind === 'drive#folder' ? 'folder' : 'file',
      path: file.path,
      modified: new Date(file.user_utime),
      downloadUrl: file.kind === 'drive#file' ? file.web_content_link : null
    })) || [];
  }

  private async getXunleiDownloadUrl(token: string, fileId: string) {
    const response = await axios.get(`https://api-pan.xunlei.com/drive/v1/files/${fileId}/download`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    return response.data.web_content_link || null;
  }

  private async getXunleiUserInfo(token: string) {
    const response = await axios.get('https://api-pan.xunlei.com/drive/v1/about', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    return {
      username: response.data.user.display_name,
      uid: response.data.user.user_id,
      quota: response.data.quota.total_space,
      used: response.data.quota.used_space
    };
  }

  // 夸克网盘实现
  private async listQuarkFiles(token: string, path: string) {
    const response = await axios.get('https://drive.quark.cn/1/clouddrive/file/list', {
      params: {
        pdir_fid: path === '/' ? '0' : path,
        limit: 100,
        order: 'updated_at',
        direction: 'DESC'
      },
      headers: {
        'Cookie': `token=${token}`
      }
    });
    
    return response.data.data?.list?.map((file: any) => ({
      id: file.fid,
      name: file.file_name,
      size: file.size || 0,
      type: file.dir ? 'folder' : 'file',
      path: file.path,
      modified: new Date(file.updated_at * 1000),
      downloadUrl: file.dir ? null : `quark://${file.fid}`
    })) || [];
  }

  private async getQuarkDownloadUrl(token: string, fileId: string) {
    const response = await axios.post('https://drive.quark.cn/1/clouddrive/file/download', {
      fids: [fileId]
    }, {
      headers: {
        'Cookie': `token=${token}`
      }
    });
    
    return response.data.data?.[0]?.download_url || null;
  }

  private async getQuarkUserInfo(token: string) {
    const response = await axios.get('https://drive.quark.cn/1/clouddrive/user/info', {
      headers: {
        'Cookie': `token=${token}`
      }
    });
    
    return {
      username: response.data.data?.nickname,
      uid: response.data.data?.uid,
      quota: response.data.data?.capacities?.total || 0,
      used: response.data.data?.capacities?.used || 0
    };
  }
}
